//
//  OtherEventsReportedViewController.m
//  Runone
//
//  Created by ekkaLyn on 2017/3/15.
//  Copyright © 2017年 runone. All rights reserved.
//  其他事件上报

#import "OtherEventsReportedViewController.h"
#import "RequestHelper.h"
#import "MJExtension.h"
#import "ParModel.h"
#import "EventBaseInfo.h"
#import "MapPointViewController.h"
#import "CityDirectionController.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "CommonUtilityjudge.h"
#import "SGImagePickerController.h"
#import "UIColor+Addition.h"
#import "SVProgressHUD.h"
#import "BCNetAPIClient.h"
#import "LittleVideoViewController.h"
#import "ROActionSheet.h"
#import "ChooseLineTableViewController.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "OtherEventMainLineViewController.h"
#import "HighWayRoadRecordDirectionInfoModel.h"

#import "ChooseDirectionView.h"
#import "SDAutoLayout.h"
#import "ChoosePileNOView.h"
#import "UnStartEventView.h"
#import "InProgressPicAndVideoView.h"
#import "PhotoesScrollView.h"
#import "AppDelegate.h"
#import "StationModel.h"


@interface OtherEventsReportedViewController ()<UIScrollViewDelegate, LittleVideoDelegate,AJPhotoPickerProtocol, AJPhotoBrowserDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate, UIAlertViewDelegate, UIPopoverPresentationControllerDelegate>{
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}
@property (nonatomic, strong) UIScrollView                    *scroollView;
@property (nonatomic, strong) UIView                          *wrapperView;
@property (nonatomic, strong) UIView                          *containerV;
@property (nonatomic, strong) ChooseDirectionView *vehicleLineV;       // 行车路线
@property (nonatomic, strong) ChoosePileNOView    *pileNOV;            // 桩号
@property (nonatomic, strong) ChooseDirectionView *vehicleDirectionV;  // 行车方向
@property (nonatomic, strong) UnStartEventView    *eventDescripV;      // 事件描述
@property (nonatomic, strong) InProgressPicAndVideoView *picAndVideoV; // 图片视频按钮
@property (nonatomic, strong) PhotoesScrollView               *photoesV;          //选中的图片的view
@property (nonatomic, strong) UIView                          *videoView;
@property (nonatomic, strong) NSURL                           *videoUrl;
@property (nonatomic, strong) NSMutableArray                  *selectPhoteArray;//选中图片

@property(nonatomic,  strong) EventBaseInfo                  *info;
@property(nonatomic         ) NSInteger code;
@property (nonatomic,   copy) NSString *directionUID;
@property (strong, nonatomic) HighwayMergeRoadRecordModel *currentModel;//当前选中的道路模型

@property(nonatomic,strong)CityDirectionController           *citypop;
@property(nonatomic,strong)OtherEventMainLineViewController  *lineVC;
@property (nonatomic, assign) NSInteger isFirstTime;
@end

@implementation OtherEventsReportedViewController

#pragma     -------其他事件上报


#pragma mark - lazy load
- (UIScrollView *)scroollView {
    if (!_scroollView) {
        _scroollView = [UIScrollView new];
        _scroollView.delegate = self;
        _scroollView.bounces  = NO;
        [self.view addSubview:_scroollView];
        _scroollView.showsVerticalScrollIndicator = YES;
        _scroollView.showsHorizontalScrollIndicator = NO;
        _scroollView.sd_layout
        .topSpaceToView(self.view, 0)
        .leftSpaceToView(self.view, 0)
        .rightSpaceToView(self.view, 0)
        .bottomSpaceToView(self.view, 0);
    }
    return _scroollView;
}
- (PhotoesScrollView *)photoesV {
    if (!_photoesV) {
        PhotoesScrollView *photoesV = [[PhotoesScrollView alloc] init];
        _photoesV = photoesV;
        [self.containerV addSubview:_photoesV];
        self.photoesV.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 16)
        .heightIs(100)
        .topSpaceToView(self.eventDescripV, 10)
        .centerXEqualToView(self.containerV)
        ;
    }
    return _photoesV;
}
- (UIView *)videoView {
    if (!_videoView) {
        UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 20, 200)];
        _videoView = newView;
//        newView.backgroundColor = [UIColor yellowColor];
        [self.containerV addSubview:_videoView];
        
    }
    return _videoView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    _info  = [[EventBaseInfo alloc] init];
    [self setUpNavigationBar];
    [self setUpUI];
    [self setUpArray];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

//设置标题
- (void) setUpNavigationBar {
    UILabel *label                = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text                    = @"其他事件上报";
    label.textAlignment           = NSTextAlignmentCenter;
    label.textColor               = [UIColor whiteColor];
    self.navigationItem.titleView = label;

    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"提 交" style:UIBarButtonItemStylePlain target:self action:@selector(report)];
}
#pragma mark- init
- (void) setUpArray {
    _selectPhoteArray = [[NSMutableArray alloc] init];
}

- (void) report {
    if (self.vehicleDirectionV.directionLabel.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"施工地点不能为空"];
        return;
    }
    if (self.pileNOV.midTextField.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"开始桩号不能为空"];
        return;
    }
    if (self.pileNOV.rightTextField.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"桩距离不能为空"];
        return;
    }
    if ([self isNumber:self.pileNOV.midTextField.text]) {
        [SVProgressHUD showSuccessWithStatus:@"请输入整形数字开始桩号"];
        return;
    }
    if ([self isNumber:self.pileNOV.rightTextField.text]) {
        [SVProgressHUD showSuccessWithStatus:@"请输入整形数字开始桩距离"];
        return;
    }
    if (self.vehicleDirectionV.directionLabel.text.length == 0  ) {
        [SVProgressHUD showSuccessWithStatus:@"行车方向不能为空"];
        return;
    }
   
    if (self.eventDescripV.desTextV.text.length == 0) {
        [SVProgressHUD showSuccessWithStatus:@"事件描述不能为空"];
        return;
    }

    [self request];
}

- (void) request {
    [SVProgressHUD showWithStatus:@"正在上报..."];
//   RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetEventDataURL;
    getCurrentEventModel.DataValue = [self dataValueJson];
    getCurrentEventModel.UpdatedTime=@"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"ReportOtherEventBaseDetailInfo";
//    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":getCurrentEventModel.MethodName,@"updatedtime":getCurrentEventModel.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":getCurrentEventModel.DataValue};
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:_selectPhoteArray videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        NSLog(@"%@",responseObjecet  );
        [SVProgressHUD showSuccessWithStatus:@"成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(NSString *)dataValueJson {
    if (!_info.Latitude&&!_info.Longitude) {
//        NSArray *arr=[[TableOperation shareInstance]  getePirNoTableOfRow:[@"K" stringByAppendingString:self.BeginPirTF.text]];
//        for (PileInfo *pir in arr) {
//            NSLog(@"%f,%f",pir.Latitude,pir.Longitude);
//            _info.Latitude=pir.Latitude;
//            _info.Longitude=pir.Longitude;
//        }
    }
    NSString *k=@"K";
    _info.BeginPile=[k stringByAppendingString:self.pileNOV.midTextField.text];
    _info.BeginPileDistance = [self.pileNOV.rightTextField.text integerValue];
    
    _info.RoadDerection     = _directionUID;
    _info.RoadDerectionName = self.vehicleDirectionV.directionLabel.text;
    _info.RoadUID           = _currentModel.RoadUID;
//    NSLog(@"%@",self.eventDescripV.desTextV.text);
    _info.IncidentDetail    = self.eventDescripV.desTextV.text;
    _info.IncidentSource    = @"2";
    _info.IncidentType      = @"10";
    
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    NSString *pileStr   = self.pileNOV.midTextField.text;
    NSString *roadPoStr = self.vehicleLineV.directionLabel.text;
    for (PileInfo *model in myDelegate.PirArray) {
        NSString *mRoadStr = model.RoadUID;
        NSString *mPileNo  = model.PileNo;
    
        if ([pileStr isEqualToString:mPileNo] && [roadPoStr isEqualToString:mRoadStr]) {
            _info.Latitude = model.Latitude ;
            _info.Longitude = model.Longitude;
        }
    }
    
    NSMutableDictionary *dic=_info.mj_keyValues;
    NSString *str=[dic mj_JSONString];
    
    ParModel *model=[[ParModel alloc] init];
    model.key=@"EventBaseInfo";
    model.value=str;
    
    NSMutableDictionary *jsonDic=model.mj_keyValues;
    NSString *json=[jsonDic mj_JSONString];
    
    NSString *strl=@"[";
    NSString *temp=[strl stringByAppendingString:json];
    NSString *str1r=@"]";
    NSString *JsonString=[temp stringByAppendingString:str1r];
    
    return JsonString;
}


- (BOOL) isNumber:(NSString *)text;
{
    NSString *regex =@"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if (![pred evaluateWithObject:text]) {
        NSLog(@"不是");
        return YES;
    }
    NSLog(@"是");
    return NO;
}

- (void) setUpUI {
    
    self.view.backgroundColor = [UIColor colorWithRed:226.0 / 255 green:230.0 / 255 blue:240.0 / 255 alpha:1];
    self.wrapperView = [UIView new];
    self.wrapperView.backgroundColor = [UIColor colorWithRed:239.0 / 255 green:239.0 / 255 blue:249.0 / 255 alpha:0.8];
    [self.scroollView addSubview:self.wrapperView];
    [self  setUpContainerV];
    [self setUpVehicleLineV];
    [self setUpPileNOV];
    [self setUpVehicleDirectionV];
    [self setUpEventDescripV];
    [self setUpPicAndVideoV];
    
    self.wrapperView.sd_layout
    .leftEqualToView(self.scroollView)
    .rightEqualToView(self.scroollView)
    .topEqualToView(self.scroollView)
    ;
    [self.containerV setupAutoHeightWithBottomView:self.eventDescripV bottomMargin:10]   ;
    [self.wrapperView setupAutoHeightWithBottomView:self.picAndVideoV bottomMargin:10]   ;
    [self.scroollView setupAutoContentSizeWithBottomView:self.wrapperView bottomMargin:0];
}
#pragma     设置UI
- (void) setUpContainerV {
    self.containerV = [[UIView alloc] init];
    [self.wrapperView addSubview:self.containerV];
    self.containerV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.wrapperView, 0)
    .autoHeightRatio(0)
    ;
}

- (void) setUpVehicleLineV {
    self.vehicleLineV = [[ChooseDirectionView alloc] initWithDefalutHeight:40.0 title:@"施 工 地 点:"];
    [self.vehicleLineV.chooseDirectBtn addTarget:self action:@selector(positionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.vehicleLineV];
    self.vehicleLineV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.containerV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpPileNOV {
    self.pileNOV = [[ChoosePileNOView alloc] initWithDefalutHeight:40.0 titleString:@" 桩      号:"];
    self.pileNOV.midTextField.keyboardType = UIKeyboardTypePhonePad;
    self.pileNOV.rightTextField.keyboardType = UIKeyboardTypePhonePad;
    [self.containerV addSubview:self.pileNOV];
    self.pileNOV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.vehicleLineV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpVehicleDirectionV {
    self.vehicleDirectionV = [[ChooseDirectionView alloc] initWithDefalutHeight:40.0 title:@"行 车 方 向:"];
    [self.vehicleDirectionV.chooseDirectBtn addTarget:self action:@selector(directionBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.containerV addSubview:self.vehicleDirectionV];
    self.vehicleDirectionV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.pileNOV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpEventDescripV {
    self.eventDescripV = [[UnStartEventView alloc] initWithDefalutHeight:40.0 title:@"事 件 描 述:"];
    [self.containerV addSubview:self.eventDescripV];
    self.eventDescripV.sd_layout
    .leftSpaceToView(self.containerV, 0)
    .topSpaceToView(self.vehicleDirectionV, 0)
    .rightSpaceToView(self.containerV, 0)
    .autoHeightRatio(0)
    ;
}
- (void) setUpPicAndVideoV {
    self.picAndVideoV = [[InProgressPicAndVideoView alloc] initWithDefalutHeight:40.0];
    [self.wrapperView addSubview:self.picAndVideoV];
    [self.picAndVideoV.picturesBtn addTarget:self action:@selector(photoesBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.picAndVideoV.videoBtn addTarget:self action:@selector(videoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.picAndVideoV.sd_layout
    .leftSpaceToView(self.wrapperView, 0)
    .rightSpaceToView(self.wrapperView, 0)
    .topSpaceToView(self.containerV, 10)
    .autoHeightRatio(0)
    ;
}
#pragma mark - 按钮点击
- (void) positionBtnClick:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    _lineVC = [[OtherEventMainLineViewController alloc] init];
    _lineVC.modalPresentationStyle = UIModalPresentationPopover;
    _lineVC.LineBlock = ^(NSString *lineStr, HighwayMergeRoadRecordModel *model) {
        weakSelf.vehicleLineV.directionLabel.text  = lineStr;
        weakSelf.currentModel = model;
        [weakSelf configDirectionText];
        [weakSelf setUpKOrLK];
    };
    _lineVC.popoverPresentationController.sourceView = sender;
    _lineVC.popoverPresentationController.delegate   = self;
    _lineVC.popoverPresentationController.sourceRect = CGRectMake(90, 5, 100, 210);
    _lineVC.popoverPresentationController.permittedArrowDirections=NO;
    [self presentViewController:_lineVC animated:YES completion:nil];
}

- (void) configDirectionText {
    HighWayRoadRecordDirectionInfoModel *directionModel= _currentModel.highWayRoadDirectionList[0];
    self.vehicleDirectionV.directionLabel.text = directionModel.DirectionDescription;
    _directionUID       = directionModel.RoadDirection;
}
- (void)setUpKOrLK {
    if ([_currentModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        UILabel *label1 = [[UILabel alloc] init];
        label1.text = @"K";
        label1.frame = CGRectMake(0, 5, 30, 40);
        self.pileNOV.midTextField.leftView     = label1;
        self.pileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
    }else {
        UILabel *label1 = [[UILabel alloc] init];
        label1.text = @"LK";
        label1.frame = CGRectMake(0, 5, 30, 40);
        self.pileNOV.midTextField.leftView     = label1;
        self.pileNOV.midTextField.leftViewMode = UITextFieldViewModeAlways;
    }
}

- (void) directionBtnClick:(UIButton *)sender {
    __weak typeof(self) weakSelf=self;
    _citypop=[[CityDirectionController alloc] init];
    _citypop.currentModel = _currentModel;
    _citypop.modalPresentationStyle=UIModalPresentationPopover;
    _citypop.popoverPresentationController.sourceView=sender;
    _citypop.popoverPresentationController.delegate=self;
    _citypop.popoverPresentationController.sourceRect=CGRectMake(140, 110, 0, 0);
    _citypop.popoverPresentationController.permittedArrowDirections=NO;
    _citypop.LineBlock = ^(NSString *directionDesStr, NSInteger roadDirection) {
        _directionUID = [NSString stringWithFormat:@"%ld",(long)roadDirection];
        weakSelf.vehicleDirectionV.directionLabel.text = directionDesStr;
    };
    [self presentViewController:_citypop animated:YES completion:nil];
}

-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}
#pragma mark -  图片和视频按钮点击
- (void) videoBtnClick {
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void) photoesBtnClick {
    if (self.selectPhoteArray.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5 - self.selectPhoteArray.count;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    if ((self.selectPhoteArray.count + assets.count) > 5)  {
        [SVProgressHUD showSuccessWithStatus:@"不能超过5张"];
        return;
    }
    [picker dismissViewControllerAnimated:NO completion:nil];
    for (int i = 0; i < assets.count; i ++) {
        ALAsset *asset =  assets[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        [self.selectPhoteArray addObject:tempImg];
    }
    _isFirstTime += 1;
    [self reConfigPhotoesView];
}

- (void) reConfigPhotoesView {
    for (UIImageView *imgV in self.photoesV.scrollV.subviews) {
        [imgV removeFromSuperview];
    }
    CGFloat x = 5;
    CGRect frame = CGRectMake(0, 0, 100, 100);
    
    self.photoesV.scrollV.contentSize = CGSizeMake(105 * self.selectPhoteArray.count + 5, 0);
    for (int i = 0 ; i < self.selectPhoteArray.count; i++) {
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds          = YES;
        imageView.image                  = self.selectPhoteArray[i];
        imageView.tag                    = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [self.photoesV.scrollV addSubview:imageView];
        
        x += frame.size.width+5;
    }
    if (_isFirstTime == 1) {
        
        if (_videoUrl) {
            [self reconfigVideoView];
        }else {
            [self.containerV setupAutoHeightWithBottomView:self.photoesV bottomMargin:10];
            [self.containerV layoutSubviews];
        }
        
    }
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.selectPhoteArray index:index];
    photoBrowserViewController.delegate = self;
    //    UIImage *img = self.selectPhoteArray[index];
    //    [self.selectPhoteArray removeObjectAtIndex:index];
    _isFirstTime += 1;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc deleteWithIndex:(NSInteger)index {
    [self.selectPhoteArray removeObjectAtIndex:index];
    //    [self.photos removeObjectAtIndex:index];
    //    [self removeDeleteImages];
    [self reConfigPhotoesView];
}

- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
    _isFirstTime += 1;
    [self reConfigPhotoesView];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        //        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        //        NSLog(@"保存到相册出错%@", error);
    }
}
// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    [self reconfigVideoView];
    [self crreatPlayViedeo:filePath];
}

- (void) reconfigVideoView {
    UIView *view;
    if (self.selectPhoteArray.count > 0) {
        view = self.photoesV;
    }else {
        view = self.eventDescripV;
    }
    
    if (_videoUrl) {
        self.videoView.sd_layout
        .widthIs([UIScreen mainScreen].bounds.size.width - 16)
        .heightIs(200)
        .topSpaceToView(view, 10)
        .centerXEqualToView(self.containerV)
        ;
        [self.containerV setupAutoHeightWithBottomView:self.videoView bottomMargin:10];
        [self.containerV layoutSubviews];
        [self.wrapperView layoutSubviews];
    }
}

- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.videoView.layer addSublayer:_playerLayer];
    [_player play];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
}

@end
